<template>
  <div class="driver-work-details-container">
    <!-- 返回按钮 -->
    <el-card class="back-card" shadow="never">
      <el-button type="primary" :icon="ArrowLeft" @click="goBack">返回司机列表</el-button>
    </el-card>

    <!-- 司机基本信息 -->
    <el-card class="driver-info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>司机基本信息</span>
        </div>
      </template>
      <el-descriptions :column="4" border>
        <el-descriptions-item label="用户ID">{{ driverInfo.userId }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ driverInfo.username }}</el-descriptions-item>
        <el-descriptions-item label="昵称">{{ driverInfo.nickname || '未填写' }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ driverInfo.phone }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ driverInfo.deptName || '未填写' }}</el-descriptions-item>
        <el-descriptions-item label="车辆编号">{{ driverInfo.vehicleNumber || '未填写' }}</el-descriptions-item>
        <el-descriptions-item label="车辆名称">{{ driverInfo.vehicleTitle || '未填写' }}</el-descriptions-item>
        <el-descriptions-item label="排班计划">{{ driverInfo.scheduleName || '未填写' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 工作记录表格 -->
    <el-card class="work-table-card" shadow="hover" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>工作记录列表</span>
          <el-button type="primary" :icon="Refresh" @click="refreshData" :loading="loading">
            刷新数据
          </el-button>
        </div>
      </template>
      
      <el-table 
        :data="groupedWorkData" 
        style="width: 100%" 
        row-key="date"
        v-loading="loading"
        :default-sort="{ prop: 'date', order: 'descending' }"
      >
        <el-table-column type="expand">
          <template #default="scope">
            <div class="work-detail-content">
              <el-table 
                :data="scope.row.records" 
                stripe 
                style="width: 100%"
                :default-sort="{ prop: 'createTime', order: 'descending' }"
              >
                <el-table-column prop="id" label="记录ID" width="80" />
                <el-table-column prop="originalFilename" label="原始文件名" width="150" show-overflow-tooltip />
                <el-table-column prop="fileType" label="文件类型" width="100" />
                <el-table-column prop="fileSize" label="文件大小" width="120">
                  <template #default="{ row }">
                    {{ formatFileSize(row.fileSize) }}
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180" sortable />
                <el-table-column prop="processStatusDisplay" label="处理状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="row.processStatus === '1' ? 'success' : 'warning'">
                      {{ row.processStatusDisplay }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="carNumber" label="车牌号" width="120" />
                <el-table-column prop="fileTag" label="文件标签" width="120" />
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="{ row }">
                    <el-button type="primary" link size="small">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="date" label="日期" width="150" sortable />
        <el-table-column prop="records" label="记录数量" width="120" sortable>
          <template #default="scope">
            <el-tag type="primary">{{ scope.row.records.length }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button 
              type="primary" 
              link
              @click="toggleExpand(scope.row)"
            >
              {{ expandedRows.includes(scope.row.date) ? '收起' : '展开' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-if="pagination.total > 0"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        :current-page="pagination.current"
        :page-sizes="[10, 20, 50]"
        :page-size="pagination.size"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ArrowLeft, Refresh } from '@element-plus/icons-vue';
import type { DriverInfo } from '@/api/types/datainfo/dataStatistics';
import { getDriverWorkDetails } from '@/api/modules/datainfo/dataStatistics';

defineOptions({
  name: 'DriverWorkDetails'
});

// Define types for the work data based on the actual API response
interface WorkRecord {
  id: number;
  monitorId: number;
  monitorDescription: string;
  originalPath: string;
  originalFilename: string;
  newFilename: string;
  storagePath: string;
  fileSize: number;
  fileType: string;
  fileUrl: string;
  processStatus: string;
  processStatusDisplay: string;
  errorMessage: string;
  processTime: string;
  fileMd5: string;
  fileTag: string;
  carNumber: string;
  carNumberRes: string;
  createTime: string;
  createDate: string;
  deptName: string;
  driverId: number;
  driverName: string;
}

interface GroupedWorkData {
  date: string;
  records: WorkRecord[];
}

// Response data structure based on the actual API response
interface DriverWorkDetailsResponse {
  current: number;
  limit: number;
  totalPage: number;
  total: number;
  rows: GroupedWorkData[];
}

const route = useRoute();
const router = useRouter();

const loading = ref(false);
const driverInfo = ref<DriverInfo>({} as DriverInfo);
const currentDriverId = ref<number>(0);
const groupedWorkData = ref<GroupedWorkData[]>([]);
const expandedRows = ref<string[]>([]);

// Pagination
const pagination = reactive({
  total: 0,
  size: 10,
  pages: 1,
  current: 1
});

// Format file size for display
const formatFileSize = (size: number): string => {
  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + ' MB';
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
  }
};

// Toggle expand row
const toggleExpand = (row: GroupedWorkData) => {
  const index = expandedRows.value.indexOf(row.date);
  if (index > -1) {
    expandedRows.value.splice(index, 1);
  } else {
    expandedRows.value.push(row.date);
  }
};

// Handle page change
const handlePageChange = (page: number) => {
  pagination.current = page;
  loadDriverWorkDetails();
};

// Handle size change
const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1; // Reset to first page
  loadDriverWorkDetails();
};

// Load driver work details
const loadDriverWorkDetails = async () => {
  if (!currentDriverId.value) return;
  
  loading.value = true;
  try {
    const response = await getDriverWorkDetails(currentDriverId.value, {
      page: pagination.current,
      limit: pagination.size
    });
    
    if (response.code === "0000") {
      groupedWorkData.value = response.data.rows || [];
      pagination.total = response.data.total || 0;
      pagination.pages = response.data.totalPage || 1;
      pagination.current = response.data.current || 1;
    } else {
      ElMessage.error(response.message || '获取工作详情失败');
    }
  } catch (error) {
    console.error('Failed to load driver work details:', error);
    ElMessage.error('获取工作详情失败');
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const refreshData = () => {
  loadDriverWorkDetails();
  ElMessage.success('数据刷新成功');
};

// 返回司机列表
const goBack = () => {
  router.push('/datalist/driversData');
};

// Initialize component
onMounted(() => {
  // Get driver ID from route params
  const driverId = route.params.driverId ? Number(route.params.driverId) : 0;
  if (driverId) {
    currentDriverId.value = driverId;
    
    // Get driver info from route query (if passed)
    if (route.query.driverInfo) {
      try {
        driverInfo.value = JSON.parse(route.query.driverInfo as string);
      } catch (e) {
        console.error('Failed to parse driver info:', e);
        // If parsing fails, we'll just show the ID
        driverInfo.value = { userId: driverId } as DriverInfo;
      }
    } else {
      // If no driver info in query, create a minimal object
      driverInfo.value = { userId: driverId } as DriverInfo;
    }
    
    // Load work details
    loadDriverWorkDetails();
  } else {
    ElMessage.error('未找到司机信息');
    goBack();
  }
});
</script>

<style scoped lang="scss">
.driver-work-details-container {
  padding: 20px;
  
  .back-card {
    margin-bottom: 20px;
  }
  
  .driver-info-card {
    margin-bottom: 20px;
  }
  
  .work-table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .work-detail-content {
    padding: 20px;
    background-color: #f8f9fa;
  }
}
</style>